/* eslint-disable react/display-name */
import {
  forwardRef, useRef, useEffect,
} from 'react';
import * as echarts from 'echarts/core';
import 'echarts-wordcloud';
import {
  LineChart, BarChart, PieChart, MapChart, TreemapChart, ScatterChart,
} from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  LegendScrollComponent,
  LegendPlainComponent,
  DataZoomComponent,
  DataZoomInsideComponent,
  DataZoomSliderComponent,
  GraphicComponent,
  DatasetComponent,
  MarkLineComponent,
  MarkPointComponent,
} from 'echarts/components';
import {
  CanvasRenderer,
} from 'echarts/renderers';
import cn from 'classnames';
import furnace from './theme';
import css from './chart.module.scss';

echarts.use(
  [TitleComponent, TooltipComponent, GridComponent, LegendComponent,
    LegendScrollComponent,
    LegendPlainComponent,
    DataZoomComponent,
    GraphicComponent,
    DataZoomInsideComponent,
    DataZoomSliderComponent,
    DatasetComponent, MarkLineComponent, MarkPointComponent,
    LineChart, BarChart, PieChart, MapChart, TreemapChart, ScatterChart,
    CanvasRenderer],
);

/**
 *
 * @param {object} props
 * @param {ECBasicOption} props.config
 * @returns
 */
interface IProps {
  notMerge?: boolean
  lazyUpdate?: boolean,
  replaceMerge?: string | string[],
  config: Record<string, any>,
  className?: string,
  onClickSeries?: () => void,
  style?: Record<string, any>,
  theme?: string,
}
const Chart = forwardRef((props: IProps, ref: any) => {
  const {
    notMerge = false, replaceMerge, lazyUpdate, config, className = '', onClickSeries, style, theme,
  } = props;
  const $chart = useRef<any>();
  const $chartDom = useRef<any>(null);

  useEffect(() => {
    echarts.registerTheme('furnace', furnace);
    $chart.current = echarts.init($chartDom.current, theme || 'furnace');
    if (ref) {
      // eslint-disable-next-line no-param-reassign
      ref.current = $chart.current;
    }
    $chart.current.on('click', 'series', onClickSeries);
    return () => {
      $chart.current.off('click');
      echarts.dispose($chart.current);
    };
  }, []);

  useEffect(() => {
    if (config) {
      $chart.current.setOption(config, {
        notMerge,
        replaceMerge,
        lazyUpdate,
      });
      $chart.current?.resize();
    }
  }, [JSON.stringify(config)]);

  useEffect(() => {
    window.addEventListener('resize', () => { $chart.current?.resize(); });
    return window.removeEventListener('resize', () => { $chart.current?.resize(); });
  }, []);

  return (
    <div className={cn(css.chart, className)} style={style}>
      <div style={{ flex: '1', position: 'relative' }}>
        <div style={{ width: '100%', height: '100%' }} ref={$chartDom} />
      </div>
    </div>
  );
});




export default Chart;
